package com.sfy.core.example;


import com.sfy.core.example.config.RegistryConfig;
import com.sfy.core.example.config.RpcConfig;
import com.sfy.core.example.constant.RpcConstant;
import com.sfy.core.example.registry.Registry;
import com.sfy.core.example.registry.RegistryFactory;
import com.sfy.core.example.utils.ConfigUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 启动类，存放了全局用到的变量，
 */

public class RpcApplication {

    /**
     * 加载配置类
     */
    private static volatile RpcConfig rpcConfig;

    private static Logger log = LoggerFactory.getLogger(RpcApplication.class);
    /**
     * 框架初始化，传入自定义配置
     * @param newRpcConfig
     */
    public static void init(RpcConfig newRpcConfig) {
        rpcConfig = newRpcConfig;
        log.info("读取到配置信息为:rpc init,config:{}", rpcConfig.toString());
        RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
        Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
        registry.init(registryConfig);
        log.info("registry init, config = {}", registryConfig);
        // 创建并注册 Shutdown Hook，JVM 退出时执行操作
        Runtime.getRuntime().addShutdownHook(new Thread(registry::destroy));
    }

    /**
     * 初始化
     */
    public static void init(){
        RpcConfig newRpcConfig;
        try{
            newRpcConfig = ConfigUtils.loadConfig(RpcConfig.class, RpcConstant.DEFAULT_CONFIG_PREFIX);
        }catch (Exception e){
            // 使用默认配置
            newRpcConfig = new RpcConfig();
        }
        init(newRpcConfig);
    }

    /**
     * 获取配置
     * @return
     */
    public static RpcConfig getRpcConfig() {
        if(rpcConfig == null){
            synchronized (RpcApplication.class){
                if(rpcConfig == null){
                    init();
                }
            }
        }
        return rpcConfig;
    }

}
